#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Hooks 动态配置系统 - 增强提交信息验证测试
测试新增的 Issue 引用和 Signed-off-by 验证功能
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from core.hook_manager import HookManager, HookType, HookContext

def test_commit_message_validation():
    """测试增强的提交信息验证"""
    print("Git Hooks Enhanced Commit Message Validation Test")
    print("=" * 60)
    
    # 确保使用正确的配置目录路径
    config_dir = project_root / "config"
    plugins_dir = project_root / "plugins"
    manager = HookManager(str(config_dir), str(plugins_dir))
    
    # 测试用例
    test_cases = [
        {
            "name": "[FAIL] 缺少 Issue 引用",
            "message": """feat: add new authentication feature

This is a detailed description of the feature.

Signed-off-by: John Doe <john.doe@huawei.com>""",
            "should_pass": False,
            "expected_error": "Issue 引用"
        },
        {
            "name": "[FAIL] 缺少 Signed-off-by",
            "message": """feat: add new authentication feature

Issue: #123
This is a detailed description of the feature.""",
            "should_pass": False,
            "expected_error": "Signed-off-by"
        },
        {
            "name": "[FAIL] 错误的邮箱域名",
            "message": """feat: add new authentication feature

Issue: #123
This is a detailed description of the feature.

Signed-off-by: John Doe <john.doe@gmail.com>""",
            "should_pass": False,
            "expected_error": "邮箱域名不符合要求"
        },
        {
            "name": "[PASS] 完整正确的提交信息 (huawei.com)",
            "message": """feat: add new authentication feature

Issue: #123
This is a detailed description of the feature.

Signed-off-by: John Doe <john.doe@huawei.com>""",
            "should_pass": True,
            "expected_error": None
        },
        {
            "name": "[PASS] 完整正确的提交信息 (h-partners.com)",
            "message": """fix: resolve login timeout issue

Fixes #456
Fixed the timeout issue in the login process.

Signed-off-by: Jane Smith <jane.smith@h-partners.com>""",
            "should_pass": True,
            "expected_error": None
        },
        {
            "name": "[PASS] 完整正确的提交信息 (huawei-partners.com)",
            "message": """docs: update API documentation

Closes #789
Updated the API documentation with new endpoints.

Signed-off-by: Bob Wilson <bob.wilson@huawei-partners.com>""",
            "should_pass": True,
            "expected_error": None
        },
        {
            "name": "[PASS] 使用 #123 格式的 Issue 引用",
            "message": """chore: update dependencies

#321
Updated all dependencies to latest versions.

Signed-off-by: Alice Brown <alice.brown@huawei.com>""",
            "should_pass": True,
            "expected_error": None
        },
        {
            "name": "[PASS] 使用 Resolves 格式的 Issue 引用",
            "message": """refactor: improve code structure

Resolves #654
Refactored the authentication module for better maintainability.

Signed-off-by: Charlie Davis <charlie.davis@h-partners.com>""",
            "should_pass": True,
            "expected_error": None
        }
    ]
    
    print(f"\n运行 {len(test_cases)} 个测试用例...\n")
    
    passed = 0
    failed = 0
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"{i}. {test_case['name']}")
        print("-" * 50)
        
        context = HookContext(hook_type=HookType.COMMIT_MSG)
        context.commit_msg = test_case['message']
        
        try:
            success = manager.execute_hook(HookType.COMMIT_MSG, context)
            
            if success == test_case['should_pass']:
                print(f"   [OK] 测试通过")
                passed += 1
            else:
                print(f"   [FAIL] 测试失败")
                print(f"   预期: {'通过' if test_case['should_pass'] else '失败'}")
                print(f"   实际: {'通过' if success else '失败'}")
                failed += 1
                
        except Exception as e:
            print(f"   [ERROR] 测试异常: {e}")
            failed += 1
        
        print()
    
    # 测试结果统计
    print("=" * 60)
    print("测试结果统计:")
    print(f"   总测试数: {len(test_cases)}")
    print(f"   通过: {passed}")
    print(f"   失败: {failed}")
    print(f"   成功率: {passed/len(test_cases)*100:.1f}%")
    
    if failed == 0:
        print("\n[SUCCESS] 所有测试都通过了！增强的提交信息验证功能工作正常。")
    else:
        print(f"\n[WARNING] 有 {failed} 个测试失败，请检查配置或代码。")
    
    return failed == 0

def show_commit_message_examples():
    """显示正确的提交信息示例"""
    print("\n" + "=" * 60)
    print("正确的提交信息格式示例:")
    print("=" * 60)
    
    examples = [
        """feat: add user authentication system

Issue: #123
Implemented OAuth 2.0 authentication with JWT tokens.
Added login, logout, and token refresh functionality.

Signed-off-by: John Doe <john.doe@huawei.com>""",
        
        """fix: resolve memory leak in data processing

Fixes #456
Fixed memory leak caused by unclosed database connections.
Added proper connection pooling and cleanup.

Signed-off-by: Jane Smith <jane.smith@h-partners.com>""",
        
        """docs: update installation guide

#789
Updated installation guide with new dependencies.
Added troubleshooting section for common issues.

Signed-off-by: Bob Wilson <bob.wilson@huawei-partners.com>"""
    ]
    
    for i, example in enumerate(examples, 1):
        print(f"\n示例 {i}:")
        print("-" * 30)
        print(example)
    
    print("\n" + "=" * 60)
    print("格式要求总结:")
    print("1. 类型: feat|fix|docs|style|refactor|test|chore")
    print("2. Issue 引用: Issue: #123 或 Fixes #123 或 #123")
    print("3. Signed-off-by: Name <email@allowed-domain.com>")
    print("4. 允许的邮箱域名:")
    print("   - h-partners.com")
    print("   - huawei-partners.com") 
    print("   - huawei.com")

def main():
    """主函数"""
    try:
        # 运行测试
        success = test_commit_message_validation()
        
        # 显示示例
        show_commit_message_examples()
        
        return 0 if success else 1
        
    except Exception as e:
        print(f"[ERROR] 测试执行失败: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
